import http from '../http/index.js'

// 接口错误信息处理
function doErrorResult(res) {
  uni.showToast({
    title: res.data.msg,
    icon: 'none'
  })
  if (res.data.result === 3) {
    uni.clearStorageSync();
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }, 1000)
  }
}

function uploadImg(callback) {
  uni.chooseImage({
    count: 1,
    crop: true,
    success: res => {
      // tempFilePath可以作为img标签的src属性显示图片
      uni.showLoading({
        title: '上传中...',
        mask: true
      })
      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: res.tempFilePaths[0],
        name: 'download',
        formData: {},
        success: res => {
          var res = JSON.parse(res.data)
          if (res.result == 1) {
            setTimeout(() => {
              uni.hideLoading();
              callback(res.data);
            }, 500)
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },
    fail: err => {
      console.log(err)
    }
  })
}

//多图上传
function uploadImgs(count, callback) {
  uni.chooseImage({
    count: count, // 默认9
    sizeType: 'compressed', // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'],
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      let tempFilePaths = res.tempFilePaths;

      for (let i = 0; i < tempFilePaths.length; i++) {
        var UploadTask = uni.uploadFile({
          url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[i],
          name: 'download',
          formData: {},
          complete: function (res) {
            callback(res.data)
          }
        })
      }
      UploadTask.onProgressUpdate((res) => {
        if (res.progress < 100) {
          uni.showLoading({
            title: '已上传' + res.progress + '%',
          })
        } else {
          uni.hideLoading();
        }
      })
    },
    fail: e => {
      console.log(e)
    }
  });
}

// 获取banner
function getBannerList(type, callback) {
  http.post('/index/Api/getBannerList', {
    type: type
  }).then((res) => {
    callback(res.data.data)
  })
}

//倒计时
function timeCountDown(time, callback) {
  var timer = setInterval(function () {
    time--
    if (time == 0) {
      clearInterval(timer)
    }
    callback(time)
  }, 1000);
}


/**
 * 获取一个数组中某个下标的取值范围
 * @param   array   arr     目标数组
 * @param   string  key     下标
 * @param   string  if_key  判断下标是否纳入取值范围
 * @param   string  type    数据类型，int:整形，float:浮点型（保留两位小数）
 * @return  string
 **/
function getSection(arr = [], key = '', if_key = '', type = 'int') {
  // 提取对象数组中的某一个属性组成新数组
  var section = []

  arr.forEach(item => {
    if (if_key) {
      if (item[if_key]) section.push(item[key])
    } else {
      section.push(item[key])
    }
  })

  // 一维数组中取出最小值
  var min = type == 'float' ? Math.min.apply(null, section).toFixed(2) : Number(Math.min.apply(null, section));
  // 一维数组中取出最大值
  var max = type == 'float' ? Math.max.apply(null, section).toFixed(2) : Number(Math.max.apply(null, section));
  // 区间
  var section_desc = min == max ? min : min + ' - ' + max;

  return section_desc;
}


function sum(arr, key) {
  var count = 0;
  if (arr.length > 0) {
    arr.forEach(function (val) {
      count += parseInt(val[key.toString()]);
    })
  }
  return count;
}

function previewImgs(imgs, current, path = 'path') {
  var imgUrls = [];

  imgs.map(x => {
    imgUrls.push(x[path])
  })
  // 生成数组
  uni.previewImage({
    current: current,
    urls: imgUrls,
  })
}

function previewImg(img) {
  if(img){
    uni.previewImage({
      urls: [img],
    })
  }
}

function doCarActive(all_check, list) {
  if (all_check) {
    list.forEach(val => {
      val.active = true;
    })
  }
  return list;
}

const  getRandomInt = () => {
  var max = 999999;
  var min = 100000;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

module.exports = {
  doErrorResult: doErrorResult,
  uploadImg: uploadImg,
  uploadImgs: uploadImgs,
  getBannerList: getBannerList,
  timeCountDown: timeCountDown,
  getSection: getSection,
  sum: sum,
  previewImgs: previewImgs,
  previewImg: previewImg,
  doCarActive: doCarActive,
  getRandomInt: getRandomInt
}
